package com.unibeta.cloudtest.mesher;

import java.io.File;
import java.io.FileFilter;
import java.util.List;
import java.util.concurrent.CompletableFuture;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;

import com.unibeta.cloudtest.mesher.config.ConfigurationProxy;
import com.unibeta.cloudtest.tool.Tools;
import com.unibeta.cloudtest.util.CloudTestUtils;
import com.unibeta.vrules.servlets.URLConfiguration;
import com.unibeta.vrules.tools.CommonSyntaxs;
import com.unibeta.vrules.utils.CommonUtils;

import cn.hutool.core.io.FileUtil;
import lombok.extern.slf4j.Slf4j;

@SpringBootApplication
@EnableJpaAuditing
@Slf4j
@EnableCaching
public class MesherApplication {

	private static final String HTTP_LOCALHOST_3927 = "http://localhost:3927";

	public static void main(String[] args) {
		ConfigurationProxy.setThreadlocalEnabled(true);
		ConfigurableApplicationContext app = SpringApplication.run(MesherApplication.class, args);
		
		refreshAPIHostToWebApps();
		cleanHistoryBinaryClasses();
	}

	private static void cleanHistoryBinaryClasses() {
		
		CompletableFuture.runAsync(()->{
			String path = ConfigurationProxy.getWorkspace();
			List<String> list = CommonUtils.searchFilesUnder(path , "^..*.bin$", "", true);

			for (String f : list) {
				CloudTestUtils.deleteFiles(f);
				new File(f).delete();
			}
		});
	}

	private static void refreshAPIHostToWebApps() {

		if (!CommonUtils.isNullOrEmpty(CommonSyntaxs.getXspringboot())
				&& CommonSyntaxs.getXspringboot().endsWith(".jar")) {

			String path= URLConfiguration.getSpringbootClasspath() + "/BOOT-INF/classes/index/assets/";
			
			File[] files = new File(path).listFiles(new FileFilter() {

				@Override
				public boolean accept(File pathname) {
					return pathname.getPath().endsWith(".js") || pathname.getPath().endsWith(".ts");
				}
			});

			for (File f : files) {
				String content = FileUtil.readUtf8String(f);
				if (!CommonUtils.isNullOrEmpty(content) && content.indexOf(HTTP_LOCALHOST_3927) > 0) {
					FileUtil.writeBytes(
							content.replace(HTTP_LOCALHOST_3927, ConfigurationProxy.getAPIHost()).getBytes(), f);
					log.info("success refreshed API host info to " + f.getName());
				}
			}
			
			
		}
	}

}
